package rensoft.portfolio.client.lib.view;

import static com.google.gwt.query.client.GQuery.$;

import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.query.client.css.CSS;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.SimplePanel;

import static cs.java.lang.Lang.is;



public class ImageButton extends SimplePanel implements MouseOverHandler, MouseOutHandler,
    MouseUpHandler, MouseDownHandler {
  private ImageResource resource;
  private ImageResource downresource;
  private ImageResource overresource;
  private Image image;

  public ImageButton() {
    setWidget(image = new Image());
    $(this).css(CSS.CURSOR.with(Cursor.POINTER));
    addDomHandler(this, MouseOverEvent.getType());
    addDomHandler(this, MouseOutEvent.getType());
    addDomHandler(this, MouseDownEvent.getType());
    addDomHandler(this, MouseUpEvent.getType());
  }

  @Override
  public void onMouseDown(MouseDownEvent event) {
    if (is(downresource)) image.setResource(downresource);
  }

  @Override
  public void onMouseOut(MouseOutEvent event) {
    image.setResource(resource);
  }

  public void onMouseOver(MouseOverEvent event) {
    if (is(overresource)) image.setResource(overresource);
  }

  @Override
  public void onMouseUp(MouseUpEvent event) {
    if (is(overresource))
      image.setResource(overresource);
    else image.setResource(resource);
  }

  public void setDown(ImageResource resource) {
    downresource = resource;
    Image.prefetch(resource.getSafeUri());
  }

  public void setImage(ImageResource resource) {
    this.resource = resource;
    image.setResource(resource);
  }

  public void setOver(ImageResource resource) {
    overresource = resource;
    Image.prefetch(resource.getSafeUri());
  }
}
